﻿namespace Nomo.PathFindingModule
{
    /// <summary>
    /// 网格图。其中，每个网格可以向它附近所有八个方向的邻居通行。
    /// </summary>
    public sealed class FreeMovableGridGraph : GridGraph
    {
        private static readonly double SquareRootOfTwo = System.Math.Sqrt(2.0);

        /// <inheritdoc />
        public FreeMovableGridGraph(int rowCount, int columnCount, System.Collections.Generic.IEnumerable<Grid> grids) : base(rowCount, columnCount, grids) { }

        /// <inheritdoc />
        protected override bool OnSearchNeighbors(Grid frontier, Grid endGrid)
        {
            foreach (var element in GetPositiveWalkableNeighbors(frontier))
            {
                if (OpenList.Contains(element) || CloseList.Contains(element))
                {
                    continue;
                }
                element.From = frontier;
                element.G    = frontier.G + 1.0;
                if (element == endGrid)
                {
                    return true;
                }
                OpenList.Add(element);
            }

            foreach (var element in GetObliqueWalkableNeighbors(frontier))
            {
                if (OpenList.Contains(element) || CloseList.Contains(element))
                {
                    continue;
                }
                element.From = frontier;
                element.G    = frontier.G + SquareRootOfTwo;
                if (element == endGrid)
                {
                    return true;
                }
                OpenList.Add(element);
            }

            return false;
        }
    }
}
